// Logistics/Login/Login.js
/*{
单元名称：登录页面js
单元功能：账号登录和免登陆直接使用
所属模块功能：
创建人：yan
创建时间：230901
修改人：
修改时间：
}*/
import {config} from "../../utils/config";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar: wx.getStorageSync('avatar'),             // 头像

    foldHeight: 0,          // 展开高度
    tabActive: 1,           // 当前激活的tab

    account: '',            // 账号
    password: '',           // 密码
    pwdChecked: true,       // 是否记住密码

    isWechatLogin: false,   // 是否免登陆直接使用
    account_w: '',          // 账号
    password_w: '',         // 密码


    sysList: [],  //系统列表
    showSys: false,  //显示系统列表选择弹窗
    active: 0,    //选中系统行
    sysName: '',
  },

  // 设置 展开 高度
  setFoldHeight() {
    let query = wx.createSelectorQuery()
    query.select('.ipts_wrap').boundingClientRect(rect => {
      this.setData({
        foldHeight: rect.height * 2,
      })
    }).exec()
  },
  // 设置 记住密码 默认值 及 填充记住的账号密码
  setRememberInfo() {
    let checked = wx.getStorageSync('checkedLoginInfo'),
      data = {
        pwdChecked: checked,
      }
    if(checked) {
      data.account = wx.getStorageSync('loginAcct')
      data.password = wx.getStorageSync('loginPwd')
    }
    this.setData(data)
  },

  // 更换 tab active
  changeTab(e) {
    this.setData({
      tabActive: e.currentTarget.dataset.i,
    })
  },

  // 双向绑定 报警告处理
  inputIpt(e) {},

  // 记住密码 onchange
  rememberPwdChange(e) {
    let checked = e.detail
    this.setData({
      pwdChecked: checked,
    })
    wx.setStorageSync('checkedLoginInfo', checked)
  },
  // 小程序用户头像昵称获取规则调整公告：https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01
  onChooseAvatar(e) {
    let { avatarUrl } = e.detail
    console.log(avatarUrl);
    this.setData({
      avatar: avatarUrl,
    })
    this.login()
  },
  // 登录/微信用户一键登录/确认绑定
  login(e) {
    let { tabActive, sysList,active, account, password, avatar} = this.data,
      {system_id,system_type} = config;
    // let post = {system_type: 'WL',system_id: sysList[active].system_id};
    let post = {system_type,system_id};

    if(!tabActive && (!account || !password)) {
      wx.$toast('请输入账号和密码！')
      return
    }
    wx.login({
      success: res =>{
        post.code = res.code;
        if (!tabActive){
          post = {...post,code: res.code,User: account,Password: password}
        }
        this.postLogin(post).then(res => {
          wx.hideLoading();
          // wx.setStorageSync('loginType','noLogin')
          // wx.setStorageSync('openid',res.data.row[0].miniprogram_OpenID)
          let {miniprogram_OpenID,token,refresh_token} = res.data.row[0] || {};
          // console.log(miniprogram_OpenID);
          let storageObj = {openid: miniprogram_OpenID,system_type};
          if (tabActive) {  //免登录直接使用
            storageObj = {
              ...storageObj,
              loginType: 'noLogin',
              refresh: refresh_token,
              token
            }

          }else { //密码登录
            // 存储登录信息
            wx.$util.setLoginStorage(res.data.row[0])
            storageObj = {
              ...storageObj,
              loginAcct: account,
              loginPwd: password,
              avatar,
              loginType: 'login',
            }
          }

          Object.entries(storageObj).forEach(([key, val]) => wx.setStorageSync(key, val))
          tabActive && this.getUserInfo(miniprogram_OpenID);
          // 跳转到首页
          this.navTo('../Index/Index')
        })
      }
    })

    /*if(tabActive) {
      // 免登录直接进去
      console.log('免登录直接进入');
      wx.login({
        success: res =>{
          post.code = res.code;
          this.postLogin(post).then(res => {
            console.log(res);
            wx.hideLoading();
            wx.setStorageSync('loginType','noLogin')
            wx.setStorageSync('openid',res.data.row[0].miniprogram_OpenID)
            this.navTo('../Index/Index')
          })
        }
      })

    } else {  // 登录

      if(!account || !password) {
        wx.$toast('请输入账号和密码！')
        return
      }
      wx.login({
        success: res =>{
          post = {...post,code: res.code,User: account,Password: password}
          this.postLogin(post).then(res => {
            wx.$toast('登录成功！')

            // 存储登录信息
            wx.$util.setLoginStorage(res.data.row[0])

            let storageObj = {
              loginAcct: account,
              loginPwd: password,
              avatar,
              loginType: 'login',
              openid: res.data.row[0].miniprogram_OpenID
            }

            Object.entries(storageObj).forEach(([key, val]) => wx.setStorageSync(key, val))

            // 跳转到首页
            this.navTo('../Index/Index')
          })
        }
      })
      // this.postLogin(account, password)
    }*/
  },

  //直接使用用户，获取用户信息
  getUserInfo(openid){

    let url = 'WXMiniProgram/get_miniprogram_customer_user_inf',
      post = {
        // "system_id": 0,
        // "unionid": "string",
        "miniprogram_OpenID": openid,
        // "offiaccount_OpenID": "string"
      };
    wx.$post(1,url,post).then(res => {
      if (res.errcode != 0) return;
      let data = res.data.row,
        name = data[0] && data[0].Nickname || openid;
      wx.setStorageSync('user_name',name)
    })
  },

  //获取微信openid

  navTo(url) {
    wx.navigateTo({
      url,
    })
  },
  postLogin(post){
    return new Promise(resolve => {
      wx.showLoading({ mask: true, });
      wx.$post(1,'Authorize/Token_miniprogram',post).then(res => {
        if (res.errcode != 0) return;
        resolve(res);
      })
    })
  },

  // 接口
  // 登录接口
  postLogin1(account, password) {
    let { avatar, } = this.data
    if(!account || !password) {
      wx.$toast('请输入账号和密码！')
      return
    }
    let post = {
      User: account,
      Password: password,
    }

    wx.showLoading({ mask: true, })
   /* setTimeout(() =>{
      wx.$toast('登录成功！');
      wx.setStorageSync('loginType','login');
      this.navTo('../Index/Index')
    },1000);*/

    wx.$post(1, 'Authorize/Token', post).then(res => {
      if(res.errcode !== 0) return
      wx.$toast('登录成功！')

      // 存储登录信息
      wx.$util.setLoginStorage(res.data.row[0])

      let storageObj = {
        loginAcct: account,
        loginPwd: password,
        avatar,
      }

      Object.entries(storageObj).forEach(([key, val]) => wx.setStorageSync(key, val))

      // 跳转到首页
      // this.navTo('../index/index')
      this.navTo('../Index/Index')
    })
  },

//230906 yan 增加获取平台数据库连接参数
  getPTConnection(){
    let url = 'WL/PTConnectionString';
    wx.$get(5,url).then(res => {
      console.log(res.errcode);
      if (res.errcode !== 0) return;
      let sysList = res.data.row || [],
        obj = {
          sysList,
          active: 0,
          sysName: sysList[0].WeChat_mini_program_name
        },
        system_id = wx.getStorageSync('system_id'),
        his = -1;
      system_id && (his = sysList.findIndex(item =>{ return item.system_id == system_id}));
      // 获取历史记录填充
      if (his >= 0) {
        obj.sysName = sysList[his].WeChat_mini_program_name;
        obj.active = his
      }
      //没有历史记录且系统列表数大于1，显示弹窗选择
      obj.showSys = his<0 && sysList.length > 1;
      console.log(obj.sysList);
      this.setData(obj)
    })
  },
  //选中系统
  chooseSys(e){
    let {index} = e.currentTarget.dataset;
    this.setData({active: index})
  },
  //确定选择系统
  selectSys(e){
    let {sysList,active} = this.data,
      data = sysList[active];
    wx.setStorageSync('system_id',data.system_id);
    this.setData({
      showSys: false,
      sysName: data.WeChat_mini_program_name
    });
  },
  //点击切换
  toggleSys(){
    this.setData({showSys: true})
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.setFoldHeight()

    //230906 yan 修改：加载登录页获取评书数据库连接参数
    // this.getPTConnection();
    //230906 end

    this.setRememberInfo()
    this.setData({
      title: wx.getStorageSync('bar_title') || ''
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // wx.login({
    //   success (res) {
    //     console.log(res);
    //     if (res.code) {

    //     //   //发起网络请求
    //     //   wx.request({
    //     //     url: 'https://example.com/onLogin',
    //     //     data: {
    //     //       code: res.code
    //     //     }
    //     //   })
    //     } else {
    //       console.log('登录失败！' + res.errMsg)
    //     }
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
